var express = require('express');
var router = express.Router();
const {v4:uuidv4} = require('uuid')
const subUserModel = require('./../model/subUserModel');
const userModel = require("./../model/usersModel");


router.get('/list',async function(req, res, next){
    let page = parseInt(req.query.page, 10);
    let pageSize = parseInt(req.query.pageSize, 10);
    let {username,phoneNum,email,uid} = req.query
    // 参数合理性检查
    if(isNaN(page) || isNaN(pageSize) || page < 1 || pageSize < 1){
        return res.status(400).send({
            code: 400,
            message: '查询参数不正确'
        });
    }
    // 计算分页跳过的文档数量
    const skipValue = (page - 1) * pageSize;
    // 构建查询条件
    let query = {};
    if (username) query.username = new RegExp(username, 'i'); // 'i' 代表忽略大小写
    if (phoneNum) query.phoneNum = new RegExp(phoneNum, 'i');
    if (email) query.email = new RegExp(email, 'i');
    if (email) query.uid = uid

    try {
        const results = await subUserModel.aggregate([
            { $match: query },
            {
                $lookup: {
                    from: "subs", // 这应该是你的订单集合名称
                    localField: "uid", // 用户集合中用于匹配的字段
                    foreignField: "uid", // 订单集合中用于匹配的字段
                    as: "userOrders" // 查询结果中的新字段名
                }
            },
            {
                $addFields: {
                    subNum: { $size: "$userOrders" }
                }
            },
            { $facet: {
                    "totalData": [{ $skip: skipValue }, { $limit: pageSize }],
                    "totalCount": [{ $count: "count" }]
                }}
        ]);
        // 从聚合结果中提取数据和计数
        const data = results[0].totalData;
        const total = results[0].totalCount[0] ? results[0].totalCount[0].count : 0;

        // 发送响应
        res.status(200).send({
            code: 0,
            data: data,
            total: total,
            currentPage:page,
            pageSize:pageSize,
            message: '查询成功'
        });

    } catch (err) {
        next(err);
    }
})

router.post('/addUser',async function (req,res,next){
    let {username,phoneNum,email} = req.body
    try{
        const existingUser = await subUserModel.findOne({ email: email });
        if(existingUser){
            // 如果用户已存在，返回错误信息
            return res.status(200).send({ // 409 Conflict 代表请求存在冲突，如数据已存在
                code: 409,
                message: '当前邮箱用户已存在!'
            });
        }
        // 如果邮箱不存在，添加新用户
        await subUserModel.create({
            username,
            phoneNum,
            email,
            createTime: new Date(),
            uid:uuidv4().split('-').join("")
        });
        res.status(200).send({
            code:0,
            message:'添加成功'
        });
    }catch(err){
        next(err);
    }
})

router.post('/upDateUser',async function (req,res,next){
    let {username,phoneNum,email,_id} = req.body
    subUserModel.updateOne(
        { "_id": _id }, // 查询条件
        { $set: { username,phoneNum,email,updateTime:new Date() }} // 更新操作
    ).then((data)=>{
        res.status(200).send({
            code:0,
            message:'修改成功'
        });
    }).catch(err=>{
        next(err);
    })
})

router.post('/delUser',async function (req,res,next){
    let {username,phoneNum,email,_id} = req.body
    subUserModel.deleteOne(
        { "_id": _id }, // 查询条件
    ).then((data)=>{
        res.status(200).send({
            code:0,
            message:'删除成功'
        });
    }).catch(err=>{
        next(err);
    })
})


module.exports = router;
